const form = layui.form
//=============================== 获取列表数据 =============================
let params = {
    advposdesc: '', //广告描述
    advposname: '', // 广告名称
    page: 1, // 页码
    limit: 5// 页数
}
async function rander(params) {
    const paramsdata = await axios.get('/ydd_advpos/list', { params })
    const { data, count } = paramsdata.data.data
    randerPage(count, params)
    randerTable(data)
}
rander(params)

//================================ 渲染表格 =============================
function randerTable(data) {
    layui.use('table', function () {
        const table = layui.table;
        //第一个实例
        table.render({
            elem: '#demo'
            , data: data
            , toolbar: '#toolbarDemo1'
            , defaultToolbar: ``
            , cols: [[ //表头
                { title: '#' }
                , { field: 'advposname', title: '广告位名称', }
                , { field: 'advposdesc', title: '广告位描述', }
                , { field: 'advposnum', title: '广告图数量', }
                , { field: 'advpossize', title: '广告位尺寸', }
                , { title: '操作', toolbar: '#toolbarDemo2' }
            ]]
            , done: async function () {
                console.log(qsa('[data-field="1"] .layui-table-cell'));
                qsa('tbody [data-field="0"] .layui-table-cell').forEach(function (ele, i) {
                    ele.innerHTML = i +1
                })
            }
        });
        //============================= 头部工具 ==============================
        table.on('toolbar(test)', function (obj) {
            if (obj.event === 'formChange') {
                const display = qs('form').style.display
                qs('form').style.display = display === 'none' ? 'flex' : 'none'
                const rotate = qs('#formChange i').style.transform
                qs('#formChange i').style.transform = rotate === 'rotate(180deg)' ? 'rotate(0)' : 'rotate(180deg)'
            }
            if (obj.event === 'refresh') {
                location.reload()
            }
            if (obj.event === 'addItem') {
                openList('addItem')
            }
        })
    });
}
function openList(btnType) {
    layer.open({
        type: 1,
        area: '850px',
        resize: false,
        shadeClose: true,
        title: btnType === 'addItem' ? '新增广告位' : '编辑广告位',
        content:
            `<form class="layui-form" lay-filter="filter" id="addOrEdit">
                <div class="layui-form-item">
                    <label class="layui-form-label" lay-verify><i>*</i>广告位名称</label>
                    <div class="layui-input-block">
                        <input type="text" name="advposname" placeholder="请输入广告位名称" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label" lay-verify><i>*</i>广告位描述</label>
                    <div class="layui-input-block">
                        <input type="text" name="advposdesc" placeholder="请输入广告位描述" autocomplete="off" class="layui-input">
                    </div>
                </div>  
                <div class="layui-form-item">
                    <label class="layui-form-label" lay-verify><i>*</i>广告位尺寸</label>
                    <div class="layui-input-block">
                        <input type="text" name="advpossize" placeholder="请输入广告位尺寸" autocomplete="off" class="layui-input">
                    </div>
                </div>                
            </form>`,
        btn: ['提交', '重置'],
        btn1: async function (index) {
            const form = layui.form
            if (!qs('[name="advposname"]').value) return layer.msg('请输入广告位名称', { time: 1000 })
            if (!qs('[name="advposdesc"]').value) return layer.msg('请输入广告位描述', { time: 1000 })
            if (!qs('[name="advpossize"]').value) return layer.msg('请输入广告位尺寸', { time: 1000 })
            await axios.post(
                btnType === 'addItem' ? `/ydd_advpos/add` : `/ydd_advpos/update`
                , 'addItem' ? form.val('filter') : btnType
            )
            rander(params)
            layer.close(index)
        },
        btn2: function () {
            const form = layui.form
            form.val('filter', {
                advposname: '',
                advposdesc: '',
                advpossize: '',
            })
            return false
        },
        anim: 5,
        success: async function (layero, index, that) {
            const form = layui.form
            if (btnType !== 'addItem') {
                const info = await axios.get('/ydd_advpos/rowInfo', { params: { id: btnType } })
                form.val('filter', info.data.data)
            }
        }
    })
}
//============================ 筛选功能 =============================
qs('#search').addEventListener('submit', async function (e) {
    e.preventDefault()
    params.advposname = qs('[name="name"]').value.trim()
    rander(params)
})
//============================= 渲染分页器 =============================
function randerPage(count, params) {
    layui.use('laypage', function () {
        const laypage = layui.laypage
        laypage.render({
            elem: 'laypage' //注意，这里的 test1 是 ID，不用加 # 号
            , count: count //数据总数，从服务端得到
            , limit: params.limit
            , curr: params.page
            , limits: [2, 3, 5, 10]
            , layout: ['count', 'limit', 'prev', 'page', 'next', 'skip']
            , theme: '#1E9FFF'
            , prev: `<i class="fa fa-angle-left left-nav-li"></i>`
            , next: `<i class="fa fa-angle-right left-nav-li"></i>`
            , jump: function (obj, first) {
                if (!first) {
                    params.page = obj.curr
                    params.limit = obj.limit
                    rander(params)
                }
            }
        });
    })
}
//================================== 行删除/编辑 =============================
qs('.layui-fluid').addEventListener('click', e => {
    const target = e.target
    /* 删除 */
    if (target.className.includes('delItem')) {
        const layer = layui.layer;
        layer.confirm('确认删除？', {
            btn: ['确认', '取消']
            , btn1: async function (index) {
                await axios.get(`/ydd_advpos/del`, { params: { id: target.dataset.id } })
                rander(params)
                layer.close(index)
            }
        });
    }
    /* 编辑 */
    if (target.className.includes('editItem')) {
        openList(target.dataset.id)
    }
})
